angular.
module('staffList').
component('staffList', {
  templateUrl:
  'views/app/staff-list/staff-list.template.html',
  controller: function ($scope,$cookies,$http,$window,$location,$rootScope,convert) {
        $scope.myRights = readCookie('rights')
        if ($scope.myRights != undefined){
          if ($scope.myRights.indexOf('user') == -1){
                      swal("没有操作权限", '请联系管理员!', "error").then(function(){
            })
          return false
        }
        
        }
        else{
          $window.location = '/login'
        }
        $scope.maxPage = 0
        $scope.currentPage = 1
        $scope.left = false
        $scope.right = false
        $scope.keyword = ''
        var condition = {}
        getUserData(condition,function(){
          paginationReset(1,1)

        })

        $scope.edit = function(index){
          $window.scopeToShare = $rootScope
           $window.open('/user_change?id=' + $scope.userData[index].cellphone)
        }

        $scope.remove = function(index){
          var id = $scope.userData[index]._id
          var name = $scope.userData[index].name
          swal({
            title: '确定要删除' + name + '吗?',
            text: "",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '删除',
            cancelButtonText : '取消'
          }).then((result) => {
            if (result.value) {
                $http({
                    method: 'post',
                    url: '/admin/removeUser',
                    data : {'id':id,'session':$cookies.get('sessionID')}
                    
                }).success(function(datax) {
                            if (datax.code == 401){
            $window.location = '/login'
            return false
          }
                  if (datax.code == 200){
                    swal(
                      '删除成功',
                      '',
                      'success'
                    )
                    getUserData(condition,function(){
                    })                             
                  }
                  else{
                    swal(
                      '出错了',
                      '',
                      'error'
                    )
                  }
         
                })                
              // swal(
              //   'Deleted!',
              //   'Your file has been deleted.',
              //   'success'
              // )
            }
          })
        }

        $scope.export = function(){

            // reuest, get res, then 
$scope.myRights = readCookie('rights')
        if ($scope.myRights != undefined){
          if ($scope.myRights.indexOf('user') == -1){
                      swal("没有操作权限", '请联系管理员!', "error").then(function(){
            })
          return false
        }
        
        }
        else{
          $window.location = '/login'
        }
            $http({
              method: 'post',
              url: '/admin/userExport',
              data : {'session':$cookies.get('sessionID')}
              
          }).success(function(datax) {
              if (datax.code != 200){
                  swal("出错了", '', "error").then(function(){
                    
                  })
                  return false                
              }
              else{
                var blob = new Blob([convert.base64ToArrayBuffer(datax.data)]);
                saveAs(new Blob([convert.base64ToArrayBuffer(datax.data)],{type:""}), "用户列表.xlsx",function(){
                  $scope.reset()
                });

              }
          })


        }

        function getUserData(query,callback){
          query.session = $cookies.get('sessionID')
          $http({
              method: 'post',
              url: '/admin/userAll',
              data : query
              
          }).success(function(datax) {
            console.log(datax)
            if (datax.code == 401){
              $window.location = '/login'
              return false
            }
            for (var i = 0 ; i  < datax.data.length ;i ++){
              datax.data[i].addDateText = formatDate(datax.data[i].date)
              datax.data[i].cellphoneText = formatCellphone(datax.data[i].cellphone)
            }
            $scope.userData = datax.data
            $scope.count = datax.count
            //paginationReset(1,1)
            callback()
          })          
        }


        function paginationReset(start,current){
          $scope.maxPage = Math.ceil($scope.count / 10)
          $scope.pages = []
          for (var i = start; i <= start + Math.min($scope.maxPage - 1, 4);i++){
            var active = i == current
            $scope.pages.push({'index':i,'active' : active})
          }

          if ($scope.currentPage == $scope.maxPage){
            $scope.right = true
          }
          else{
            $scope.right = false
          }

          if ($scope.currentPage == 1){
            $scope.left = true
          }
          else{
            $scope.left = false
          }
        }



        $scope.changePage = function(index){
          if ($scope.currentPage != index){
          var start = 1
          $scope.currentPage = index
          if ($scope.maxPage < index + 4){
            start = Math.max(1, $scope.maxPage - 4)
          }
          else{
            start = index
          }
          condition.offset = (index - 1) * 10
          paginationReset(start,index)
          getUserData(condition,function(){
          
          })
        }
      }

      $scope.prevPage = function(){
        if ($scope.currentPage != 1){
        $scope.changePage($scope.currentPage - 1)
      }
      }
      $scope.nextPage = function(){
        if ($scope.currentPage != $scope.maxPage){
          $scope.changePage($scope.currentPage + 1)
      }

      }

      $scope.search = function(){
        condition = {}
        condition.keyword = $scope.keyword
        paginationReset(1,1)

        getUserData(condition,function(){
                  
        })        
      }


      $scope.sort = function(index){
        var order = -1
        var query = ''
        if (index == 0 ){
          query = 'addDate'
        }


        if (condition[query] != undefined){
          order = condition[query] * -1
        }
        condition = {}
        if ($scope.keyword != ''){
          condition.keyword = $scope.keyword
        }
        condition[query] = order
        condition.offset = 0
        paginationReset(1,1)

        getUserData(condition,function(){        
        })
      }
      function formatDate(date){
        var xdate = new Date(date)
        var year = xdate.getFullYear()
        var day = xdate.getDate()
        var month = xdate.getMonth()
        var hour = xdate.getHours()
        var minute = xdate.getMinutes()
        return String(year) + '-' + String(month+1) + '-' + String(day) + ' ' + String(addZeroBefore(hour)) + ':' + String(addZeroBefore(minute))
      }

      function formatCellphone(data){
        console.log(data)
        return String(data).substr(0,3) + '****' +String(data).substr(7,10) 
      }


      function addZeroBefore(n) {
        return (n < 10 ? '0' : '') + n;
      }

  }
})



